package com.lee9213.conference.track.management.format;

import com.lee9213.conference.track.management.constant.Constant;
import com.lee9213.conference.track.management.entity.TalkEntity;
import com.lee9213.conference.track.management.enums.TalkTypeEnum;
import com.lee9213.conference.track.management.exception.FileFormatException;
import com.lee9213.conference.track.management.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 会话解析实现类
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2018-07-11 12:21
 */
public class TalkParse implements Parse {

    private static final Logger LOGGER = LoggerFactory.getLogger(TalkParse.class);

    private static final Pattern INPUT_TEXT_PATTERN = Pattern.compile("^(.+)\\s(\\d+)?\\s?((min)|(lightning))$");

    @Override
    public List<TalkEntity> parse(List<String> textList) throws FileFormatException {
        List<TalkEntity> talkEntities = new ArrayList<>();
        textList.forEach(text -> {
            Matcher match = INPUT_TEXT_PATTERN.matcher(text);

            if (!match.find()) {
                LOGGER.error("【{}】格式错误", text);
                throw new FileFormatException("【" + text + "】格式错误");
            }
            // 获取会话标题
            String title = match.group(1);

            // 获取会话类型
            String talkType = match.group(3);
            TalkTypeEnum talkTypeEnum;
            if (TalkTypeEnum.MINUTES.getName().equalsIgnoreCase(talkType)) {
                talkTypeEnum = TalkTypeEnum.MINUTES;
            } else {
                talkTypeEnum = TalkTypeEnum.LIGHTNING;
            }

            // 获取会话时长
            String minuteString = match.group(2);
            int minutes = StringUtil.isNullOrEmpty(minuteString) ? 1 : Integer.parseInt(minuteString);
            minutes = minutes * talkTypeEnum.getValue();

            // 判断时长是否超过约定时长
            if (minutes > Constant.MAX_DURATION) {
                LOGGER.error("【{}】格式错误，超过约定最大时长{}min", text, Constant.MAX_DURATION);
                throw new FileFormatException("【" + text + "】格式错误，超过约定最大时长" + Constant.MAX_DURATION + "min");
            }
            TalkEntity talkEntity = new TalkEntity(title, talkTypeEnum.getName(), minutes);
            talkEntities.add(talkEntity);
        });


        return talkEntities;
    }
}
